package net.sea.setup.action.ext.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sea.commons.context.AppContext;
import net.sea.commons.util.ELUtils;
import net.sea.commons.util.ELUtils.EL;
import net.sea.commons.util.InstallMsgUtils;
import net.sea.commons.util.PropertiesUtils;
import net.sea.commons.util.StringUtils;
import net.sea.setup.action.AbstractAction;
import net.sea.setup.action.constants.Constants;
import net.sea.setup.enums.CfgFilePosition;
import net.sea.setup.enums.CfgMapping;

/**
 * 
 * 配置文件修改操作
 *
 * @author huachengwu 
 */
public class ConfigAction extends AbstractAction {

	/*
	 * 配置文件修改方法
	 * 
	 * @see
	 * com.ec.setup.action.IAction#install(net.sea.commons.context.AppContext,
	 * java.util.Map)
	 */
	@Override
	public void install(AppContext context, Map<String, String> parMap) {
		logger.info(parMap.get(Constants.INSTALL_DESC_KEY));
		long startTime = System.currentTimeMillis();
		String cfgType = parMap.get(Constants.CFG_TYPE_KEY);
		if (logger.isDebugEnabled()) {
			logger.debug("配置文件类型：" + cfgType);
		}
		String cfgFilePosition = parMap.get(Constants.CFG_FILE_POSITION_KEY);
		if (logger.isDebugEnabled()) {
			logger.debug("配置文件位置：" + cfgFilePosition);
		}
		String cfgFile = parMap.get(Constants.CFG_FILE_KEY);
		if (logger.isDebugEnabled()) {
			logger.debug("配置文件：" + cfgFile);
		}

		Map<String, String> params = new HashMap<String, String>();
		// 获取需要修改的配置信息
		CfgMapping cfgMapping = CfgMapping.valueOf(cfgType);
		Map<String, String> mapping = cfgMapping.getMapping();
		Set<String> keySet = mapping.keySet();
		for (String key : keySet) {
			String value = (String) context.getAttribute(key);
			if(StringUtils.isBlank(value)){
				continue;
			}
			params.put(mapping.get(key), value);
		}
		if (logger.isDebugEnabled()) {
			logger.debug("修改的参数为：" + params);
		}

		// 替换EL变量
		List<EL> els = ELUtils.getVarName(cfgFile);
		for (EL el : els) {
			String value = (String) context.getAttribute(el.getVarName());
			cfgFile = cfgFile.replace(el.getElExp(), value.replace("\\", "/"));
		}
		InstallMsgUtils.setInstallMsg("修改配置文件【" + new File(cfgFile).getName()
				+ "】");
		if (logger.isDebugEnabled()) {
			logger.debug("实际配置文件为：" + cfgFile);
		}

		// 处理不同位置的配置文件
		CfgFilePosition cfgFilePos = CfgFilePosition.valueOf(cfgFilePosition);
		if (cfgFilePos == CfgFilePosition.dir) {
			PropertiesUtils.modifyCfgInDir(cfgFile, params);
		} else if (cfgFilePos == CfgFilePosition.jar) {
			try {
				String[] files = cfgFile.split("!");
				PropertiesUtils.modifyCfgInJar(files[0], files[1], params);
			} catch (FileNotFoundException e) {
				throw new RuntimeException(e);
			}
		}
		long endTime = System.currentTimeMillis();
		if (logger.isDebugEnabled()) {
			logger.debug("操作执行时间：" + (endTime - startTime) / 1000.0 + "秒");
		}
	}

	@Override
	public void uninstall(AppContext context, Map<String, String> parMap) {

	}
}
